package com.ssy.jt808.gateway.application.endpoint;

import com.ssy.jt808.gateway.application.service.TerminalAppService;
import com.ssy.jt808.gateway.domain.pojo.TerminalInfo;
import com.ssy.jt808.gateway.infrastructure.enums.SessionAttribute;
import com.ssy.jt808.protocol.basics.JTMessage;
import com.ssy.netmc.core.model.Message;
import com.ssy.netmc.session.Session;
import com.ssy.netmc.session.SessionListener;

import java.util.function.BiConsumer;

public class JTSessionListener implements SessionListener {

    private static final BiConsumer<Session, Message> REQUEST_INTERCEPTOR = ( session, message) -> {
        JTMessage request = (JTMessage) message;
        request.setClientId(session.getClientId());
        request.setSerialNo(session.nextSerialNo());

        if (request.getMessageId() == 0) {
            request.setMessageId(request.reflectMessageId());
        }

      TerminalInfo device = SessionAttribute.doGetTerminalInfo(session);
        if (device != null) {
            int protocolVersion = device.getProtocolVersion();
            if (protocolVersion > 0) {
                request.setVersion(true);
                request.setProtocolVersion(protocolVersion);
            }
        }
    };

    public TerminalAppService terminalStatusService;

    public JTSessionListener( TerminalAppService terminalStatusService ){
        this.terminalStatusService = terminalStatusService;
    }


    @Override
    public void sessionCreated(Session session) {
        session.requestInterceptor(REQUEST_INTERCEPTOR);
    }

    @Override
    public void sessionRegistered(Session session) {
    }

    @Override
    public void sessionDestroyed(Session session) {
        this.terminalStatusService.onOffline(session.getClientId());
    }
}